<template>
  <div class="app-container">
     <h2>登陆成功，页面将在5秒内跳转到首页</h2>
     token: {{ token }}<br>
     user: {{ user }}
  </div>
</template>

<script lang="ts" setup name="CallBack">
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store/user";
import { useCodeVerifierStore } from "@/store/code-verifier";
import {
  getToken as getCodeToken,
  getInfo,
  logOut,
} from "../../api/token";
const router = useRouter();
const codeVerifierStore = useCodeVerifierStore();
const userStore = useUserStore();
const user = ref(userStore.userInfo);


const index = ref(0);

// 定义响应式变量来存储查询参数
const code = ref<string | null>(null);
const state = ref<string | null>(null);
const issuer = ref<string | null>(null);
const token = ref<string | null>(null);

onMounted(async () => {
  // 获取当前 URL
  const urlParams = new URLSearchParams(window.location.search);

  // 提取查询参数
  code.value = urlParams.get("code");
  state.value = urlParams.get("state");
  issuer.value = urlParams.get("iss");
  token.value = await getToken(urlParams);
  if (token.value) {
    await getUserInfo();
  }
  
  // router.replace('/');
});

const getToken = async (urlParams) => {
  if (localStorage.getItem("token") && urlParams.size === 0) {
    return localStorage.getItem("token");
  }
  if (!code.value) {
    ElMessage.error("授权码未找到");
    return;
  }
  const codeVerifier = codeVerifierStore.codeVerifier;
  
  if (!codeVerifier) {
    ElMessage.error("code_verifier未找到");
    return;
  }
  const callbackPath = router.resolve({ path: "/callback" }).href;
  const absoluteCallbackUrl = window.location.origin + callbackPath;

  try {
    const params = new URLSearchParams({
      grant_type: "authorization_code",
      code: code.value,
      redirect_uri: absoluteCallbackUrl,
      client_id: import.meta.env.VITE_CLIENT_ID,
      client_secret: import.meta.env.VITE_CLIENT_SECRET,
      code_verifier: codeVerifier, // 必须提供！
    });
    const tokenResponse = await getCodeToken(params);
    localStorage.setItem("token", tokenResponse.access_token);
    localStorage.setItem("refresh_token", tokenResponse.refresh_token);
    
    return tokenResponse.access_token;
  } catch (error) {
    console.error("Error exchanging authorization code for tokens:", error);
  }
};


const getUserInfo = async () => {
  if(userStore.isAuthenticate){
    user.value = userStore.userInfo;
    return;
  }
  user.value = await getInfo();
  userStore.addUserInfo(user.value);
}; 


</script>

<style lang="scss" scoped>
.side {
  height: calc(100vh - 60px);
  width: 100%;
}
.header {
  height: 60px;
  width: 100%;
  // background-color: red;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-right: 20px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

.el-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  color: white;
}
</style>